package org.apache.rocketmq.console.shiro.controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.rocketmq.console.config.LoginConfigure;
import org.apache.rocketmq.console.config.RMQConfigure;
import org.apache.rocketmq.console.script.dao.DeptInfoDao;
import org.apache.rocketmq.console.script.dao.EnvironDicDao;
import org.apache.rocketmq.console.script.dao.RegionInfoDao;
import org.apache.rocketmq.console.script.model.DeptInfo;
import org.apache.rocketmq.console.script.model.EnvironDic;
import org.apache.rocketmq.console.script.model.RegionInfo;
import org.apache.rocketmq.console.script.service.EnvService;
import org.apache.rocketmq.console.shiro.entity.UserInfo;
import org.apache.rocketmq.console.shiro.sevice.UserInfoService;
import org.apache.rocketmq.console.support.JsonResult;
import org.apache.rocketmq.console.util.JsonUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/shiro")
public class ShiroController {
	@Autowired
	private RMQConfigure rmqConfigure;
	@Autowired
	private UserInfoService userInfoService;
	// private Logger logger = LoggerFactory.getLogger(EnvController.class);
	@Autowired
	public EnvService envService;
	@Resource
	private DeptInfoDao deptInfoDao;
	@Resource
	private LoginConfigure loginConfigure;
	@Autowired
	public RegionInfoDao regionInfoDao;
	@Autowired
	public EnvironDicDao environDicDao;

	@RequestMapping("/listRegionConsole")
	@ResponseBody
	public JsonResult<String> listRegionConsole() {
		List<EnvironDic> findAll = environDicDao.findAll();
		String jsonString = JSON.toJSONString(findAll);
		return new JsonResult<String>(jsonString);
	}

	@RequestMapping("/getRegionName")
	@ResponseBody
	public JsonResult<String> getRegionName() {
		EnvironDic environDic = rmqConfigure.getCurrentRegion();
		if (environDic != null) {
			return new JsonResult<String>("RMQ控制台-" + environDic.getRegionName());
		} else {
			return new JsonResult<String>("RMQ控制台");
		}

	}

	@SuppressWarnings({ "unchecked" })
	@RequestMapping("/login")
	@ResponseBody
	public JsonResult<String> login(@RequestParam("username") String username,
			@RequestParam("password") String password, Model model) {
		Subject currentUser = SecurityUtils.getSubject();
		String msg = "";
		if (!currentUser.isAuthenticated()) {
			// 把用户名和密码封装为 UsernamePasswordToken 对象
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			// rememberme
			token.setRememberMe(true);

			try {
				// 执行登录.
				currentUser.login(token);
			} catch (UnknownAccountException uae) {
				System.out.println("UnknownAccountException -- > 账号不存在：");
				msg = "用户名或密码不正确.";
				currentUser.logout();
				return new JsonResult<String>(1, "1", msg);
			} catch (IncorrectCredentialsException ice) {
				System.out.println("IncorrectCredentialsException -- > 密码不正确：");
				msg = "密码不正确";
				currentUser.logout();
				return new JsonResult<String>(1, "1", msg);
			}
			// 所有认证时异常的父类.
			catch (AuthenticationException ae) {
				// unexpected condition? error?
				System.out.println("登录失败: " + ae.getMessage());
				msg = "用户名或密码不正确";
				currentUser.logout();
				return new JsonResult<String>(1, "1", msg);
			}
		}
		EnvironDic environDic = rmqConfigure.getCurrentRegion();
		String deptCode = null;
		String deptName = null;
		// UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		UserInfo userInfo = userInfoService.findByUsername(username);
		UserInfo currentUserInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
		// UumsResult result = loginConfigure.loginByUUMS(token).getResult();
		deptCode = currentUserInfo.getDeptCode();
		deptName = currentUserInfo.getDeptName();
		// if (deptCode == null || "".equals(deptCode)) {
		if (userInfo != null && userInfo.getPermissionId() == 1) {
			return new JsonResult<String>(0, "0", msg);
		} /*
			 * else { msg = "请用oa用户名密码登录"; currentUser.logout(); return new
			 * JsonResult<String>(1, "1", msg); }
			 */

		// }
		

		if (environDic != null) {
			String regionCode = environDic.getRegionCode();
			RegionInfo regionInfo = regionInfoDao.findOneByCode(regionCode);
			String deptCodes = regionInfo.getDeptCodes();
			List<String> deptCodesList = JsonUtil.string2Obj(deptCodes, List.class);
			if (deptCodesList == null || !deptCodesList.contains(deptCode)) {
				msg = "当前用户所属部门:" + deptName + ",无权访问该域的控制台,请联系运维配置权限,部门编号" + deptCode;
				currentUser.logout();
				return new JsonResult<String>(1, "1", msg);
			}

		} else {
			msg = "此控制台配置的nameserver:" + rmqConfigure.getNamesrvAddr() + "不属于任何域，请联系管理员添加";
			currentUser.logout();
			return new JsonResult<String>(1, "1", msg);
		}
		if (userInfo != null && userInfo.getPermissionId() == 2) {
			return new JsonResult<String>(0, "0", msg);
		}
		
		DeptInfo deptInfo = deptInfoDao.findOneByCode(currentUserInfo.getDeptCode());
		// List deptSysCodesList = null;
		String deptSysCodes = deptInfo.getSysCodes();
		if (deptSysCodes == null || "".equals(deptSysCodes)) {
			msg = "当前用户:" + username + ",部门编号:" + deptCode + "没有配置可以访问系统的权限,请联系运维在部门中配置系统权限";
			currentUser.logout();
			return new JsonResult<String>(1, "1", msg);
		}
		/*
		 * if (deptSysCodesList == null) { deptSysCodesList = new LinkedList<String>();
		 * } if (sysCodes == null && deptSysCodesList.size() < 1) { msg = "当前用户:" +
		 * username + ",部门编号:" + deptCode + "没有配置可以访问系统的权限,请联系运维在部门中配置系统权限";
		 * currentUser.logout(); return new JsonResult<String>(1, "1", msg); }
		 */
		// model.addAttribute("msg", msg);
		model.addAttribute("msg", msg);
		return new JsonResult<String>(0, "0", msg);
		// return "redirect:/index.html";
	}

	@RequestMapping("/403")
	public String unauthorizedRole() {
		System.out.println("------没有权限-------");
		return "403";
	}

}